{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy \n",
    "import gensim\n",
    "import numpy as np\n",
    "from jieba import analyse\n",
    "from gensim.models import Word2Vec\n",
    "from gensim.models.word2vec import LineSentence"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "与‘文化’相似度最高的10个词：\n",
      "[('交流', 0.6815170645713806), ('民间', 0.6793422102928162), ('地理', 0.6765635013580322), ('娱乐', 0.6653778553009033), ('地域', 0.6645703315734863), ('艺术', 0.663486897945404), ('现代', 0.65007084608078), ('哲学', 0.6495169401168823), ('天地', 0.6275594830513), ('道德', 0.6259422898292542)]\n"
     ]
    }
   ],
   "source": [
    "def train_word2vec():\n",
    "    cor_data=open('TrainData.txt','r',encoding='utf-8')\n",
    "    model=Word2Vec(LineSentence(cor_data),sg=0,vector_size=200,window=5,min_count=5,workers=9)\n",
    "    model.save('model_word2vec')\n",
    "    print(\"与‘文化’相似度最高的10个词：\")\n",
    "    print(model.wv.most_similar('文化',topn=10))\n",
    "train_word2vec()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def keyword(data):\n",
    "    tfidf=analyse.extract_tags\n",
    "    keywords=tfidf(data)\n",
    "    return keywords"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_keywords(docpath,savepath):\n",
    "    with  open(docpath, 'r', encoding='utf-8')as docf,open(savepath,'w')as ouf:\n",
    "        for data in docf:\n",
    "            data=data[:len(data)-1]\n",
    "            keywords=keyword(data)\n",
    "            for word in keywords:\n",
    "                outf.write(word+' ')\n",
    "            outf.write('\\n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_pos(string,char):\n",
    "    space_pos=[]\n",
    "    try:\n",
    "        space_pos=list(((pos)for pos,val in enumerate(string)if(val == char)))\n",
    "    except:\n",
    "            pass\n",
    "    return space_pos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_vector(file_name,model):\n",
    "    with open(file_name,'r')as f:\n",
    "        wordvec_size=200\n",
    "        word_vector=numpy.zeros(wordvec_size)\n",
    "        for data in f:\n",
    "            space_pos=get_pos(data,' ')\n",
    "            first_word=data[0:space_pos[0]]\n",
    "            if model.wv.__contains__(first_word):\n",
    "                word_vector=word_vector+model.wv[first_word]\n",
    "            for i in range(len(space_pos)-1):\n",
    "                word=data[space_pos[i]:space_pos[i+1]]\n",
    "                if model.wv.__contains__(word):\n",
    "                    word_vector=word_vector+model.wv[word]\n",
    "        return word_vector"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "def similarity(vector1,vector2):\n",
    "    vector1_abs=np.sqrt(vector1.dot(vector1))\n",
    "    vector2_abs=np.sqrt(vector2.dot(vector2))\n",
    "    if vector2_abs !=0 and vector1_abs !=0:\n",
    "        similarity = (vector1.dot(vector2))/(vector1_abs * vector2_abs)\n",
    "    else:\n",
    "        similarity = 0\n",
    "    return similarity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "def main():\n",
    "    model=gensim.models.Word2Vec.load('model_word2vec')\n",
    "    new1='new1.txt'\n",
    "    new2='new2.txt'\n",
    "    new1_keywords='new1_keywords.txt'\n",
    "    new2_keywords='new2_keywords.txt'\n",
    "    get_keywords(new1,new1_keywords)\n",
    "    get_keywords(new2,new2_keywords)\n",
    "    new1_vector=get_vector(new1_keywords,model)\n",
    "    print('文本new1的部分向量:\\n',new1_vector[:20])\n",
    "    new2_vector=get_vector(new2_keywords,model)\n",
    "    print('文本new2的部分向量:\\n',new2_vector[:20])\n",
    "    print('文本new1和文本new2的相似度：',similarity(new1_vector,new2_vector ))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Building prefix dict from the default dictionary ...\n",
      "Dumping model to file cache C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\jieba.cache\n",
      "Loading model cost 0.821 seconds.\n",
      "Prefix dict has been built successfully.\n"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'outf' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-18-972361fa1b80>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[1;33m==\u001b[0m \u001b[1;34m\"__main__\"\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m     \u001b[0mmain\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;32m<ipython-input-15-ed69cbc3ec96>\u001b[0m in \u001b[0;36mmain\u001b[1;34m()\u001b[0m\n\u001b[0;32m      5\u001b[0m     \u001b[0mnew1_keywords\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'new1_keywords.txt'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      6\u001b[0m     \u001b[0mnew2_keywords\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'new2_keywords.txt'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 7\u001b[1;33m     \u001b[0mget_keywords\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnew1\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mnew1_keywords\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      8\u001b[0m     \u001b[0mget_keywords\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnew2\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mnew2_keywords\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      9\u001b[0m     \u001b[0mnew1_vector\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mget_vector\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnew1_keywords\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mmodel\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m<ipython-input-6-f1be76304abc>\u001b[0m in \u001b[0;36mget_keywords\u001b[1;34m(docpath, savepath)\u001b[0m\n\u001b[0;32m      5\u001b[0m             \u001b[0mkeywords\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mkeyword\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      6\u001b[0m             \u001b[1;32mfor\u001b[0m \u001b[0mword\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mkeywords\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 7\u001b[1;33m                 \u001b[0moutf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mword\u001b[0m\u001b[1;33m+\u001b[0m\u001b[1;34m' '\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      8\u001b[0m             \u001b[0moutf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'\\n'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mNameError\u001b[0m: name 'outf' is not defined"
     ]
    }
   ],
   "source": [
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
